<template>
  <template v-if="hasInfo">
    <lottery-info  :info="info" />
    <template v-if="hasPrizes && !isOpened">
        <lottery-count-down :prizes="prizes" />
        <lottery-condition :prizes="prizes" />
        <lottery-prize :prizes="prizes" />
    </template>
    <template v-else>
        <lottery-result :prizes="prizes" />
    </template>                    
    <div class="tip">该抽奖已自动过滤异常行为，请以开奖结果为准</div>
  </template>
</template>

<script>
import { reactive, toRefs, computed, watch } from 'vue'
import LotteryInfo from './info'
import LotteryCountDown from './countDown'
import LotteryCondition from './condition'
import LotteryPrize from './prize'
import LotteryResult from './result'
import { lotteryApi } from '@/api'
export default {
  name: 'Lottery',
  components: {
    LotteryInfo,
    LotteryCountDown,
    LotteryCondition,
    LotteryPrize,
    LotteryResult
  },
  props: {
    id: {
      type: [Number, String],
      required: true
    }
  },
  setup(props) {
    const params = reactive({
      info: null,
      prizes: null,
      hasInfo: computed(() => !!params.info),
      hasPrizes: computed(() => !!params.prizes),
      isOpened: computed(() => params.prizes?.status === 2 ?? false)
    })

    const init = async () => {
      try {
        await getInfo()
        await getPrizes()
      } catch (error) {
        console.log(error)
      }
    }
    const getInfo = async () => {
      try {
        const { data } = await lotteryApi.getDetail({
          dynamic_id: props.id
        })
        if (data) {
          params.info = data.card
        }            
      } catch (error) {
        throw new Error(error)
      }
    }
    const getPrizes = async () => {
      try {
        const { data } = await lotteryApi.getPrize({
            business_id: props.id
        })
        if (data) {
          params.prizes = data
        }
      } catch (error) {
        console.log(error)
      }
    }

    watch(() => props.id, () => {
      init()
    }, {
      immediate: true
    })

    return {
      ...toRefs(params)
    }
  }
}
</script>

<style lang="scss" scoped>
  .tip{
    padding: 10px 0;
    font-size: 12px;
    color: $color-text-secondary;
    text-align: center;
  }
</style>